#!/bin/bash

# CX - Codex with OpenRouter
# 简化版cx命令，使用OpenRouter API
# 支持多个模型和流式输出

# 颜色定义
CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 默认配置
MODEL="openai/gpt-5"  # 改为默认使用GPT-5
API_KEY="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"
TEMPERATURE=0.3
MAX_TOKENS=3000

# 处理参数
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    echo -e "${CYAN}CX - AI编程助手 (OpenRouter版)${NC}"
    echo ""
    echo "用法:"
    echo "  cx <问题>               # 使用默认模型(GPT-5)"
    echo "  cx -m <模型> <问题>     # 指定模型"
    echo ""
    echo "示例:"
    echo "  cx 分析代码安全问题"
    echo "  cx -m openai/gpt-4o 优化数据库查询"
    echo "  cx -m google/gemini-2.5-flash 解释这段代码"
    echo ""
    echo "可用模型:"
    echo "  openai/gpt-5          - GPT-5 (默认,最强)"
    echo "  openai/gpt-4o          - GPT-4o (快速,推荐)"
    echo "  google/gemini-2.5-pro  - Gemini 2.5 Pro"
    echo "  google/gemini-2.5-flash - Gemini 2.5 Flash (快速)"
    exit 0
fi

# 检查是否指定模型
if [ "$1" = "-m" ]; then
    MODEL="$2"
    shift 2
fi

PROMPT="$*"

if [ -z "$PROMPT" ]; then
    echo -e "${RED}错误: 请提供问题${NC}"
    echo "使用 'cx --help' 查看帮助"
    exit 1
fi

echo -e "${CYAN}🤖 使用模型: $MODEL${NC}"
echo -e "${GREEN}💭 正在思考...${NC}"
echo ""

# 调用OpenRouter API
RESPONSE=$(curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -H "HTTP-Referer: https://github.com/hxci-campus-portal" \
  -H "X-Title: CX Command" \
  -d "{
    \"model\": \"$MODEL\",
    \"messages\": [
      {\"role\": \"system\", \"content\": \"You are an expert programming assistant. Provide clear, concise code suggestions and analysis. Answer in the same language as the user's question. For Chinese questions, answer in Chinese.\"},
      {\"role\": \"user\", \"content\": \"$PROMPT\"}
    ],
    \"temperature\": $TEMPERATURE,
    \"max_tokens\": $MAX_TOKENS
  }")

# 提取响应内容
CONTENT=$(echo "$RESPONSE" | jq -r '.choices[0].message.content' 2>/dev/null)

if [ "$CONTENT" = "null" ] || [ -z "$CONTENT" ]; then
    echo -e "${RED}错误: 获取响应失败${NC}"
    echo "$RESPONSE" | jq '.' 2>/dev/null
    exit 1
fi

# 输出响应
echo "$CONTENT"